package com.bjSoft.regressionTestTool.core.codeCoverage.action;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;

import cfg.CFG;

public class CFGHandler {
	/**
	 * 
	 * @param project
	 *  the project to generate the CFGs.
	 * @throws CoreException
	 * @throws CFGException 
	 * @throws ClassNotFoundException 
	 */
	public static void generateAllCFGs(IProject project) throws CoreException, CFGException, ClassNotFoundException {
		IFolder folder = project.getFolder("coverage_CFGs");
		if (!folder.exists()) {
			folder.create(true, true, null);
			if (!folder.exists()) {
				throw new CFGException("Error, creating the folder coverage_cgfs");
			}
		}
		generateAllCFGs(project.members());
	}	
	
	private static void generateAllCFGs(IResource[] resources) throws CoreException, ClassNotFoundException {
		for (int i = 0; i < resources.length; i++) {
			IResource res = resources[i];
			if (res instanceof IFolder) {
				IFolder folder = (IFolder) res;
				generateAllCFGs(folder.members());
			} else if (res instanceof IFile) {
				IFile file = (IFile) res;
				if (file.getFileExtension().equalsIgnoreCase("class")) {
					String classLocation = file.getLocation().toOSString();
					classLocation = classLocation.substring(0, classLocation.length() - 6);
					IPath path = res.getProject().getLocation();
					String packagePath = res.getFullPath().toPortableString();
					for (int j = 0; j < 3; j++) {
						int index = packagePath.indexOf("/");
						packagePath = packagePath.substring(index + 1, packagePath.length());
					}
					packagePath = packagePath.substring(0, packagePath.length() - 6);
					if (!classLocation.contains("_covCase")) {
						CFG.runCFG(
								classLocation, path.toOSString() 
								+ "\\coverage_CFGs\\", packagePath);
					}
				
				} 				
			} 			                         
		}
	}

	public static void clearNewCFGFolder(IProject project) throws CoreException {
		IFolder folder = project.getFolder("new_CFGs");
		if (folder.exists()) {
			deleteContains(folder.members());
		}
		
	}

	private static void deleteContains(IResource[] resources) throws CoreException {
		for (int i = 0; i < resources.length; i++) {
			IResource res = resources[i];
			if (res instanceof IFolder) {
				IFolder folder = (IFolder) res;
				deleteContains(folder.members());
			} else if (res instanceof IFile) {
				IFile file = (IFile) res;
				file.delete(true, null);				
			} 			                         
		}
		
	}
}
